package cn.stronglink.assetmanage.business.patrol.view;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.renderscript.AllocationAdapter;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSmoothScroller;
import android.support.v7.widget.RecyclerView;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.stronglink.assetmanage.BaseActivity;
import cn.stronglink.assetmanage.MyApplication;
import cn.stronglink.assetmanage.R;
import cn.stronglink.assetmanage.business.patrol.adapter.PatrolListAlreadyAdapter;
import cn.stronglink.assetmanage.business.patrol.adapter.PatrolListWaitAdapter;
import cn.stronglink.assetmanage.dao.DaoManager;
import cn.stronglink.assetmanage.dao.SyncTypesDao;
import cn.stronglink.assetmanage.entity.Patrol;
import cn.stronglink.assetmanage.entity.Result;
import cn.stronglink.assetmanage.entity.SearchAsset;
import cn.stronglink.assetmanage.entity.SyncTypes;
import cn.stronglink.assetmanage.entity.Task;
import cn.stronglink.assetmanage.entity.User;
import cn.stronglink.assetmanage.listener.onRecyclerListener;
import cn.stronglink.assetmanage.utils.Constants;
import cn.stronglink.assetmanage.utils.LogUtil;
import cn.stronglink.assetmanage.utils.ToastUtil;
import cn.stronglink.assetmanage.utils.dao.PatrolDataUtil;
import cn.stronglink.netrequest.business.patrol.PatrolService;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.CertificatePinner;
import okhttp3.Response;

import static cn.stronglink.assetmanage.utils.dao.PatrolDataUtil.savePatrolData;

/**
 * 1为未巡检 2为处理中 3为已巡检
 */
public class PatrolActivity extends BaseActivity implements View.OnClickListener,
        onRecyclerListener, View.OnTouchListener {
    private static final String TAG = "PatrolActivity";
    private Button btn_patrol_already;
    private Button btn_patrol_wait;
    private RecyclerView patrol_list;
    private TextView tv_patrol_createOrExecute_time;
    private TextView tv_patrol_createOrExecute_person;
    private TextView tv_patrol_finishOrExecute_time;
    private TextView tv_patrol_uploadOrExecutePerson;
    private SwipeRefreshLayout sfl_patrol_order;


    private PatrolListAlreadyAdapter patrolListAlreadyAdapter;
    private PatrolListWaitAdapter patrolListWaitAdapter;
    private LinearLayoutManager layoutManager;

    private List<Patrol> patrolList = new ArrayList<>();//盘点单列表
    private List<Patrol> wait_patrolList = new ArrayList<>();//待盘点单列表
    private List<Patrol> already_patrolList = new ArrayList<>();//已盘点单列表

    private int waitnum = 0;    //待盘点数量
    private int alreadynum = 0;  //已盘点数量
    private int status = Constants.STATUS_ONE;     //默认显示待盘点

    private PatrolService patrolService;
    private float mPosX, mCurPosX;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_patrol);
        try {
            initView();
            initData();
        } catch (Exception e) {
            LogUtil.e(TAG, e.getMessage());
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            setSelectPosition(3);
            initData();
            changeColor(Constants.STATUS_ONE);
        } catch (Exception e) {
            LogUtil.e(TAG, e.getMessage());
        }
    }

    private void initView() {
        btn_patrol_wait = findViewById(R.id.btn_patrol_wait);
        btn_patrol_already = findViewById(R.id.btn_patrol_already);
        patrol_list = findViewById(R.id.patrol_list);
        tv_patrol_createOrExecute_time = findViewById(R.id.tv_patrol_createOrExecute_time);
        tv_patrol_createOrExecute_person = findViewById(R.id.tv_patrol_createOrExecute_person);
        tv_patrol_finishOrExecute_time = findViewById(R.id.tv_patrol_finishOrExecute_time);
        tv_patrol_uploadOrExecutePerson = findViewById(R.id.tv_patrol_uploadOrExecutePerson);
        sfl_patrol_order = findViewById(R.id.sfl_patrol_order);
        patrolService = new PatrolService();
        sfl_patrol_order.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshPatrolData();
            }
        });

        btn_patrol_already.setOnClickListener(this);
        btn_patrol_wait.setOnClickListener(this);

        patrolListWaitAdapter = new PatrolListWaitAdapter(this, null);
        patrolListAlreadyAdapter = new PatrolListAlreadyAdapter(this, null);
        layoutManager = new LinearLayoutManager(this,
                LinearLayoutManager.VERTICAL, false);
        patrol_list.setLayoutManager(layoutManager);
        //默认第一次加载为待巡检单
        patrolListWaitAdapter.setListener(this);
        patrol_list.setAdapter(patrolListWaitAdapter);
        patrol_list.setOnTouchListener(this);
    }


    private void initData() {
        //获取巡检单
        showPatrolData();
        //默认为待盘点选中
        btn_patrol_wait.setClickable(true);
        changeColor(status);
        changeText();
        refreshWaitList(wait_patrolList);
    }


    /**
     * 刷新数据
     */
    private void refreshPatrolData() {
        //判断是离线还是在线
        SyncTypes syncTypes = DaoManager.getDaoSession(this).getSyncTypesDao().
                queryBuilder().where(SyncTypesDao.Properties.IsSelected.eq(true)).unique();
        int tp = Constants.STATUS_TWO;
        if (syncTypes != null) {
            tp = syncTypes.getSyscTs();
        }
        switch (tp) {
            case Constants.STATUS_ONE:
                //自动
                getPatrolService();
                break;
            case Constants.STATUS_TWO:
                //离线，从数据库拿数据
                initData();
                stopRefresh();
                ToastUtil.toastShort("本地数据加载完成");
                break;
            default:
                stopRefresh();
                break;
        }
    }

    @Override
    public void onItemClicked(View v, int postion) {
        try {
            //进入详情页面
            Patrol patrol = new Patrol();
            if (status == Constants.STATUS_ONE) {
                //未巡检
                patrol = wait_patrolList.get(postion);
            } else {
                patrol = already_patrolList.get(postion);
            }

            Intent intent = new Intent(this, PatrolDetailActivity.class);
            String patrol_id = patrol.getId_() + "";
            intent.putExtra("patrolDetail", patrol_id);
            startActivity(intent);
        } catch (Exception e) {
            LogUtil.e(TAG, e.getMessage());
        }
    }

    private void getPatrolService() {
        if (patrolService != null) {
            try {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String jsonResult = patrolService.downloadPatrolWorkOrder(User.getInstance().getId_());
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    stopRefresh();

                                }
                            });
                            if(PatrolDataUtil.savePatrolData(jsonResult)){
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        initData();
                                        ToastUtil.toastShort("更新完成");
                                    }
                                });
                            }else{
                                ToastUtil.toastShort("更新失败");
                            }
                        } catch (final Exception e) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    ToastUtil.toastShort(e.getMessage());
                                }
                            });
                        }
                    }
                }).start();
            } catch (Exception e) {
                ToastUtil.toastShort(e.getMessage());
                stopRefresh();
            }
        }
    }


    /**
     * 停止刷新
     */
    private void stopRefresh() {
        if (sfl_patrol_order != null) {
            sfl_patrol_order.setRefreshing(false);
        }
    }

    //改变button的text
    private void changeText() {
        btn_patrol_wait.setText("待巡检(" + waitnum + ")");
        btn_patrol_already.setText("已巡检(" + alreadynum + ")");
    }


    private void showPatrolData() {
        patrolList = PatrolDataUtil.getPatrol();
        waitnum = 0;
        alreadynum = 0;
        wait_patrolList.clear();
        already_patrolList.clear();
        //判断是已盘点还是未盘点
        for (Patrol patrol : patrolList) {
            if (patrol.getStatus() == Constants.STATUS_ONE) {
                //1是未巡检
                wait_patrolList.add(patrol);
            } else {
                already_patrolList.add(patrol);
            }
        }
        waitnum = wait_patrolList.size();
        alreadynum = already_patrolList.size();
    }

    //刷新列表
    private void refreshWaitList(List<Patrol> patrolList) {
        patrolListWaitAdapter.setListener(this);
        patrol_list.setAdapter(patrolListWaitAdapter);
        patrolListWaitAdapter.notifyDatasChanged(patrolList);
    }

    //刷新列表
    private void refreshAlreadyList(List<Patrol> patrolList) {
        patrolListAlreadyAdapter.setListener(this);
        patrol_list.setAdapter(patrolListAlreadyAdapter);
        patrolListAlreadyAdapter.notifyDatasChanged(patrolList);
    }

    //改变待巡检已巡检颜色和显示的text信息
    private void changeColor(int status) {
        if (status == Constants.STATUS_ONE) {
            btn_patrol_wait.setBackground(null);
            btn_patrol_wait.setTextColor(getResources().getColor(R.color.blue_inventory_text));
            btn_patrol_already.setBackgroundColor(getResources().getColor(R.color.gray_inventory_btn));
            btn_patrol_already.setTextColor(Color.BLACK);

            tv_patrol_createOrExecute_time.setText("创建时间");
            tv_patrol_createOrExecute_person.setText("创建人");
            tv_patrol_finishOrExecute_time.setText("计划执行时间");
            tv_patrol_uploadOrExecutePerson.setText("执行人");
        } else {
            btn_patrol_already.setBackground(null);
            btn_patrol_already.setTextColor(getResources().getColor(R.color.blue_inventory_text));
            btn_patrol_wait.setBackgroundColor(getResources().getColor(R.color.gray_inventory_btn));
            btn_patrol_wait.setTextColor(Color.BLACK);

            tv_patrol_createOrExecute_time.setText("计划执行时间");
            tv_patrol_createOrExecute_person.setText("执行人");
            tv_patrol_finishOrExecute_time.setText("完成时间");
            tv_patrol_uploadOrExecutePerson.setText("上传状态");
        }


    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.btn_patrol_already:
                try {
                    refreshAlreadyList(already_patrolList);
                    status = Constants.STATUS_THREE;
                    changeColor(status);
                } catch (Exception e) {
                    LogUtil.e(TAG, e.getMessage());
                }
                break;
            case R.id.btn_patrol_wait:
                try {
                    refreshWaitList(wait_patrolList);
                    status = Constants.STATUS_ONE;
                    changeColor(status);
                } catch (Exception e) {
                    LogUtil.e(TAG, e.getMessage());
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onBackPressed() {

    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        try {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    mPosX = event.getX();
                    break;
                case MotionEvent.ACTION_MOVE:
                    mCurPosX = event.getX();
                    break;
                case MotionEvent.ACTION_UP:
                    if (mCurPosX - mPosX > 0
                            && (Math.abs(mCurPosX - mPosX) > Constants.FLUSH_DISTANCE)) {
                        //向左滑動，显示待盘点
                        if (status != Constants.STATUS_ONE) {
                            refreshWaitList(wait_patrolList);
                            status = Constants.STATUS_ONE;
                            changeColor(status);
                        }
                        return true;
                    } else if (mCurPosX - mPosX < 0
                            && (Math.abs(mCurPosX - mPosX) > Constants.FLUSH_DISTANCE)) {
                        //向右滑动，显示已盘点
                        if (status != Constants.STATUS_THREE) {
                            refreshAlreadyList(already_patrolList);
                            status = Constants.STATUS_THREE;
                            changeColor(status);
                        }
                        return true;
                    }
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            LogUtil.e(TAG, e.getMessage());
        }

        return false;
    }
}
